<template>
  <div class="content-container">
    <el-form label-width="auto" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="物流商编号" class="full-width">
            <el-input v-model="filters.carrierNo" placeholder="请输入物流商编号" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物流商姓名" class="full-width">
            <el-input v-model="filters.carrierName" placeholder="请输入物流商姓名" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物流商类型" class="full-width">
            <el-select v-model="filters.carrierType" placeholder="请选择物流商类型" class="full-width">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="第三方平台" :value="0"></el-option>
              <el-option label="平台提供" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" class="full-width">
            <el-select v-model="filters.activeStatus" placeholder="请选择状态" class="full-width">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="未生效" :value="0"></el-option>
              <el-option label="生效 " :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人姓名" class="full-width">
            <el-input v-model="filters.contactPerson" placeholder="请输入负责人姓名" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物流商地址" class="full-width">
            <el-input v-model="filters.carrierAddress" placeholder="请输入物流商地址" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="right full-width" label=" ">
            <el-button-group class="full-width">
              <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
              <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
            </el-button-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="divider"></div>
    <el-row :gutter="20" class="action-buttons">
      <el-col :span="12">
        <el-button type="primary" plain icon="plus" @click="openDialog(null,false)">新建</el-button>
        <el-button type="danger" plain icon="delete" @click="openBatchDeleteDialog">删除</el-button>
      </el-col>
    </el-row>
    <el-table :data="currentTableData"
              style="width: 100%;
              flex: 1"
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              :default-sort="{ prop: 'generateDate', order: 'descending' }">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="carrierNo" label="物流商编号"min-width="100"></el-table-column>
      <el-table-column prop="carrierName" label="物流商名称" min-width="150"></el-table-column>

      <el-table-column prop="carrierType" label="物流商类型" min-width="140">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.carrierType === 0 ? 'success' : 'warning'"
              disable-transitions>
            {{ scope.row.carrierType === 0 ? '第三方平台' : '平台提供' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="activeState" label="状态" min-width="140">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.activeStatus === 0 ? 'danger' : 'warning'"
              disable-transitions
          >{{ scope.row.activeStatus === 0 ? '未生效' : '已生效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="carrierAddress" label="物流商地址" min-width="160"></el-table-column>
      <el-table-column prop="contactPerson" label="联系人姓名" min-width="160">
      </el-table-column>
      <el-table-column prop="contactPhone" label="联系人电话" min-width="160">
      </el-table-column>
      <el-table-column prop="contactEmail" label="联系邮箱" min-width="160">
      </el-table-column>
      <el-table-column prop="generateDate" label="创建时间" sortable width="160">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.generateDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button @click="openDialog(scope.row,true)" type="text" icon="EditPen" style="font-size: 13px">修改
          </el-button>
          <el-button
              @click="openCarrierShowDialog(scope.row)"
              type="text"
              icon="Document" style="font-size: 13px">
            详情
          </el-button>
          <el-popconfirm
              width="200"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon-color="#626AEF"
              title="是否确定删除？"
              @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button type="text" size="small" icon="delete" style="font-size: 13px">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"
        class="fixed-pagination">
    </el-pagination>
    <NewCarrierDialog
        v-model="dialogVisible"
        @update:visible="dialogVisible = $event"
        :data="selectedCarrier"
        :isEdit="isEdit"
        @save="handleSave"
        visible/>

    <carrierShowDialog
        v-model="carrierShowVisible"
        :order="selectedCarrier"
        @close="carrierShowVisible = false"
    />
    <!-- 批量删除弹框 -->
    <el-dialog
        title="删除物流商"
        align-center
        v-model="batchDeleteVisible"
        width="60%"
        style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"
    >
      <el-table
          :data="selectedCarriers"
          style="width: 100%;
          margin-bottom: 40px;
          margin-top: 20px;"
          stripe
          border
      >
        <el-table-column prop="carrierNo" label="物流商编号" width="100"></el-table-column>
        <el-table-column prop="carrierName" label="物流商名称" width="150"></el-table-column>
        <el-table-column prop="carrierType" label="物流商类型" width="140">
          <template v-slot="scope">
            <el-tag
                :type="scope.row.carrierType === 0 ? 'success' : 'warning'"
                disable-transitions>
              {{ scope.row.carrierType === 0 ? '第三方平台' : '平台提供' }}
            </el-tag>
          </template>
        </el-table-column><el-table-column prop = 0 label="状态" width="140">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.activeStatus === 0 ? 'danger' : 'warning'"
              disable-transitions
          >{{ scope.row.activeStatus === 0 ? '未生效' : '已生效' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="carrierAddress" label="物流商地址" width="160"></el-table-column>
        <el-table-column prop="contactPerson" label="联系人姓名" width="160">
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系方式" width="160">
        </el-table-column>
        <el-table-column prop="contactEmail" label="联系邮箱" width="160">
        </el-table-column>
        <el-table-column prop="generateDate" label="创建时间" sortable width="160">
          <template v-slot="scope">
            <span>{{ formatDate(scope.row.generateDate) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDeleteVisible = false" type="primary" plain>取消</el-button>
        <el-button type="danger" @click="handleBatchDelete" plain>确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import {listCarrierInfo, addCarrierInfo, updateCarrierInfo, deleteCarrierInfo, deleteCarriers} from '@/api/delivery/carrier.js';
import NewCarrierDialog from "@/views/delivery/carrier/NewCarrierDialog.vue"; // 引入新建/编辑对话框组件
import carrierShowDialog from "@/views/delivery/carrier/carrierShowDialog.vue";
export default {
  components: {NewCarrierDialog,carrierShowDialog},
  setup() {
    const filters = reactive({
      carrierNo: '',
      carrierName: '',
      carrierType: null,
      activeStatus: null,
      carrierAddress: '',
      contactPhone: '',
      contactPerson: '',
    });

    const dialogVisible = ref(false);
    const selectedCarrier = ref({});
    const isEdit = ref(false);

    const currentTableData = ref([]);
    const total = ref(0);
    const pageSize = ref(8);
    const currentPage = ref(1);

    const openDialog = (carrier, edit) => {
      dialogVisible.value = true;
      isEdit.value = edit;
      selectedCarrier.value = carrier || {};
    };

    const carrierShowVisible = ref(false);
    const openCarrierShowDialog = (order) => {
      selectedCarrier.value = order;
      carrierShowVisible.value = true;
      console.log(order);
    };
    const handleSave = async (carrierData) => {
      try {
        if (isEdit.value) {
          await updateCarrierInfo(carrierData);
        } else {
          await addCarrierInfo(carrierData);
        }

        dialogVisible.value = false;
        search();
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    const handleDelete = async (row) => {
      try {
        await deleteCarrierInfo(row.carrierNo);
        if (currentTableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value -= 1;
        }
        search();
      } catch (error) {
        console.error('删除失败:', error);
      }
    };

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    const search = async () => {
      const query = {
        carrierNo: filters.carrierNo,
        carrierName: filters.carrierName,
        carrierType: filters.carrierType,
        activeStatus: filters.activeStatus,
        carrierAddress: filters.carrierAddress,
        contactPerson: filters.contactPerson,
        page: currentPage.value,
        pageSize: pageSize.value,
      };
      try {
        const response = await listCarrierInfo(query);
        currentTableData.value = response.data;
        total.value = response.total;
      } catch (error) {
        console.error('获取物流商信息失败:', error);
      }
    };

    //批量删除
    const selectedCarriers = ref([]); // 存储选中的物流商信息
    const batchDeleteVisible = ref(false); // 控制批量删除弹框显示

    // 打开批量删除弹框
    const openBatchDeleteDialog = () => {
      if (selectedCarriers.value.length === 0) {
        return ElMessage.warning("请选择要删除的物流商！");
      }
      console.log("selectedCarriers", selectedCarriers.value);
      batchDeleteVisible.value = true;
      console.log("batchDeleteVisible", batchDeleteVisible.value);
    };

    // 批量删除
    const handleBatchDelete = async () => {
      if (selectedCarriers.value.length === 0) {
        return ElMessage.warning("请选择要删除的物流商！");
      }
      const carrierNos = selectedCarriers.value.map((item) => item.carrierNo); // 获取选中车辆的车辆编码
      console.log(carrierNos);
      try {
        await deleteCarriers(carrierNos); // 调用批量删除接口
        ElMessage.success("批量删除成功！");
        batchDeleteVisible.value = false; // 关闭弹框
        search(); // 刷新表格数据
      } catch (error) {
        console.error("批量删除失败：", error);
      }
    };

    // 表格主选择框选中时触发
    const handleSelectionChange = (rows) => {
      selectedCarriers.value = rows;
      console.log(`选中的物流商个数: ${rows.length}`);
    };

    const resetFilters = () => {
      filters.carrierNo = '';
      filters.carrierName = '';
      filters.carrierType = null;
      filters.activeStatus = null;
      filters.carrierAddress = '';
      filters.contactPerson = '';
      currentPage.value = 1;
      search();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      search();
    };

    onMounted(() => {
      search();
    });

    return {
      filters,
      currentTableData,
      total,
      pageSize,
      currentPage,
      formatDate,
      search,
      resetFilters,
      handleCurrentChange,
      dialogVisible,
      selectedCarrier,
      isEdit,
      openDialog,
      handleSave,
      handleDelete,
      selectedCarriers,
      openBatchDeleteDialog,
      batchDeleteVisible,
      handleBatchDelete,
      handleSelectionChange,
      openCarrierShowDialog,
      carrierShowVisible,
    };
  },
};
</script>

<style scoped>
.content-container {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  max-width: calc(100% - 40px);
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-left: 20px;
  margin-top: 15px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  text-align: center;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.fixed-pagination {
  position: relative;
  right: 0;
  align-self: end;
  margin-top: 20px;
}
</style>
